package com.ml.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ml.admin.service.SmsService;
import com.ml.admin.utils.*;
import com.zhenzi.sms.ZhenziSmsClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ml
 * @date 2023/3/16 11:27
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    RedisService redisService;


    @Value("${sms.apiUrl}")
    private String apiUrl;
    @Value("${sms.appId}")
    private String appId;
    @Value("${sms.appSecret}")
    private String appSecret;
    /**
     * 对接榛子云平台 发送短信验证码
     * @param phone 手机号
     * @return 成功 or 失败
     */
    @Override
    public ReturnResponse sendSms(String phone) throws Exception {
        if (StringUtils.isBlank(phone)){
            return ReturnResponse.failure(ResponseEnum.PARAM_NOT_COMPLETE);
        }
        //调用榛子云api
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", "11343");
        String[] templateParams = new String[2];
        String phoneCode = mailUtil.CreateCode();
        templateParams[0] = phoneCode;
        templateParams[1] = "3分钟";
        params.put("templateParams", templateParams);
        String result = client.send(params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String data = jsonObject.getString("data");
        if ("0".equals(code)){
            //设置3min验证码缓存
            redisService.setString(CommonConstant.PHONE_CODE+phone,phoneCode,3*60L);
            log.info("{}|手机验证码发送成功，验证码为{}",phone,phoneCode);
            return ReturnResponse.success(data);
        }
        return ReturnResponse.failure();
    }
}
